package com.bclz;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.bclz.load.JDBCConnection;

public class App {

	public static void main(String[] args) throws Exception {
		long a = Instant.now().toEpochMilli();
		BufferedReader in = new BufferedReader(new FileReader(new File("E:\\快乐8.txt")), 5 * 1024 * 1024);
		Connection connection = JDBCConnection.getConnection();

		connection.setAutoCommit(false);
		System.out.println("默认的事务隔离级别:" + connection.getTransactionIsolation());

		Map<Integer, List<String>> collect = in.lines().parallel().map(str1 -> {

			String[] split = str1.split(",");
			int[] array = Arrays.stream(split).skip(1).limit(20).mapToInt(Integer::parseInt).sorted().toArray();
			String first = String.valueOf(array[0] + array[1] + array[2] + array[3] + array[4] + array[5]);
			String second = String.valueOf(array[6] + array[7] + array[8] + array[9] + array[10] + array[11]);
			String third = String.valueOf(array[12] + array[13] + array[14] + array[15] + array[16] + array[17]);
			int winningNumber = Integer.parseInt(first.substring(first.length() - 1, first.length()))
					+ Integer.parseInt(second.substring(second.length() - 1, second.length()))
					+ Integer.parseInt(third.substring(third.length() - 1, third.length()));

			return "(" + Integer.parseInt(split[0]) + "," + winningNumber + "," + (winningNumber > 13 ? 1 : 0) + ","
					+ (winningNumber % 2 == 0 ? 0 : 1) + "),";
		}).collect(Collectors.groupingBy(sr -> (sr.hashCode() > 0 ? sr.hashCode() : -sr.hashCode()) % 50));

		System.out.println(Instant.now().toEpochMilli() - a);

		collect.values().parallelStream().forEach(st -> {
			try {
				// long k=Instant.now().toEpochMilli();
				Optional<String> reduce = st.parallelStream().reduce((st1, st2) -> st1 + st2);

				PreparedStatement statement = connection
						.prepareStatement("insert into happy_data (id,winning,big_small,even_odd) values "
								+ reduce.get().substring(0, reduce.get().length() - 1));
				statement.addBatch();
				statement.executeBatch();
				connection.commit();
				// System.out.println(Thread.currentThread().getId() + " Already End...");
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println(e);
			}

		});

		in.close();
		System.out.println(Instant.now().toEpochMilli() - a);
	}

}
